<?php
/**
 * Created by littleU.
 * User: littleU
 * Date: 2021-02-03
 * Time: 16:28
 */

namespace app\common\tool\qiniu;


use app\lib\exception\FileNotExistException;
use app\lib\exception\ParameterException;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;
class Upload
{
    private $file;

    public function __construct()
    {
        if(empty($_FILES['file']['tmp_name']))
        {
            throw new  FileNotExistException();
        }
        $this->file = $_FILES['file']['tmp_name'];
    }

    public function uploadToDefault()
    {
        $uploadMgr = new UploadManager();
        $token = $this->getToken();
        $key = $this->getFileKey();
        list($result, $error) = $uploadMgr->putFile($token, $key, $this->file);
        if($error !== null)
        {
            return json([
                'code' => config('code.error'),
                'msg'  => $error
            ]);
        }
        else
        {
            return json([
                'code' => config('code.success'),
                'msg' => '上传成功',
                'data' => [
                    'src' => config('qiniu.bucket_domain').'/'.$key
                ]
            ]);
        }
    }

    private function getToken()
    {
        $auth = new Auth(config('qiniu.ak'), config('qiniu.sk'));
        $token = $auth->uploadToken(config('qiniu.bucket'));
        return $token;
    }

    private function getFileKey()
    {
        $pathInfo = pathinfo($_FILES['file']['name']);
        $ext = $pathInfo['extension'];
        $key  = date('Y')."/".date('m')."/".date('YmdHis').rand(0, 9999).substr(md5($this->file), 0, 5).'.'.$ext;
        return $key;
    }

    public function uploadToBucket($fileDir, $fileName)
    {
        $token = $this->getToken();
        $key = $this->getBucketKey($fileDir, $fileName);
        $uploadMgr = new UploadManager();
        list($ret, $error) = $uploadMgr->putFile($token, $key, $this->file);
        if($error !== null)
        {
            return json([
                'code' => config('code.error'),
                'msg'  => $error
            ]);
        }
        else
        {
            return json([
                'code' => config('code.success'),
                'msg' => '上传成功',
                'data' => [
                    'src' => config('qiniu.bucket_domain').'/'.$key
                ]
            ]);
        }
    }

    private function getBucketKey($fileDir, $fileName)
    {
        $pathInfo = pathinfo($_FILES['file']['name']);
        $ext = $pathInfo['extension'];
        $key = $fileDir.'/'.$fileName.'.'.$ext;
        return $key;
    }
}